package org.example.sse.controller;

import lombok.extern.slf4j.Slf4j;
import org.example.sse.config.OkHttpStreamClient;
import org.example.sse.config.SseEmitterUTF8;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

@Slf4j
@RestController
@RequestMapping(value = "/chat")
public class ChatController {

    private final OkHttpStreamClient okHttpStreamClient;

    @Autowired
    public ChatController(OkHttpStreamClient okHttpStreamClient) {
        this.okHttpStreamClient = okHttpStreamClient;
    }

    /**
     * 模拟流式结果输出
     */
    @GetMapping(value = "chat", produces = {MediaType.TEXT_EVENT_STREAM_VALUE})
    public SseEmitter chat() {
        SseEmitter emitter = new SseEmitterUTF8(60000L);
        okHttpStreamClient.stream(emitter, "http://localhost:8080/sse");
        return emitter;
    }
}